/*
  表单
  用于包裹一组TextField,简化数据校验操作
 */

import 'package:flutter/material.dart';

void main() => runApp(MaterialApp(
  home: Scaffold(
    appBar: AppBar(
      title: Text('表单'),
    ),
    body: HomePage(),
  ),
));


class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {

  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();

  late String _name, _pwd;

  @override
  Widget build(BuildContext context) {
    return Form(
        key: _formKey,
        child:Column(
          children: [
            TextFormField(
              decoration: InputDecoration(hintText: '请输入账号'),
              onSaved: (String? value){
                _name = value!;
              },
              validator: (String? value) {
                return value!.length>=6?null:'最少6个字符';
              },
            ),
            TextFormField(
              decoration: InputDecoration(hintText: '请输入密码'),
              // 键盘类型
              keyboardType: TextInputType.visiblePassword,
              // 显示成密码类型
              obscureText: true,
              onSaved: (String? value){
                _pwd = value!;
              },
              validator: (String? value) {
                return value!.length>=6?null:'最少6个字符';
              },
            ),
            TextButton(onPressed: (){
              var _state = _formKey.currentState;
              // 执行每个TextFormField的校验方法validator
              if (_state!.validate()) {
                // 执行每个TextFormField的保存方法
                _state.save();
                // 执行登录
                debugPrint('执行登录');
              }
            }, child: Text('登录'))
          ],
        )
    );
  }
}

